<script setup>
import { onMounted, ref } from "vue";
import { Edit, Delete, View } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import {
  postPaperApply,
  postPaperSearch,
  postPaperDel,
  postPaperAdminSearch,
  postPaperEvidence,
  postPaperAdminApplicate,
  postPaperLevel,
  postPaperAdminExport,
  postPaperAdminMulApplicate,
  postPaperAdminDownloadEvidence,
  postPaperAdminUpdate,
} from "@/api/paper";
import { useUserStore } from "@/store";
import "dayjs/locale/zh-cn";
import { SrtingToNum, levelSrtingToNum } from "@/utils/typeMap";
import { convertISOToBasicString } from "@/utils/common1";
import { id } from "element-plus/es/locales.mjs";
const userStore = useUserStore();
function checkRole(s) {
  if (userStore.userRole.includes("ROLE_ADMIN")) {
    // console.log("这不是没有嘛", userStore.userRole);
    if (s >= 4) return true;
    else return false;
  }
  if (s == 4) return true;
  return false;
}
const selectform = ref({
  status: "",
  type: "",
  finalLevel: "",
  stuName: "", //改成姓名
  startTime: "",
  endTime: "",
  stuClass: "",
});

const removeSelectForm = async () => {
  selectform.value = {};
  pagenum.value = 1;
  getApproveList();
};

const timestg = ref([]); //需要分割字符串

const shortcuts = [
  {
    text: "Last week",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "Last month",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "Last 3 months",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];
const form = ref(); //用于校验

const total = ref(0);
const pagenum = ref(1);
const pagesize = ref(7);
const datalist = ref([]); //用来存返回的数据
const multipleTableRef = ref();
const multipleSelection = ref([]);

const selectable = (row) => ![1, 2].includes(row.id);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  // console.log("val", val);
};

const getApproveList = async () => {
  // console.log("getApproveList", selectform.value);
  // console.log("getApproveList");
  // console.log(timestg.value[0]);
  if (timestg.value != "") {
    //分割字符串，以,分割怎么写
    selectform.value.startTime = convertISOToBasicString(timestg.value[0]);
    selectform.value.endTime = convertISOToBasicString(timestg.value[1]);
  }
  if (selectform.value.finalLevel != "")
    selectform.value.finalLevel = levelSrtingToNum(selectform.value.finalLevel);
  // console.log("selectform", selectform.value);
  const res = await postPaperAdminSearch(
    pagenum.value,
    pagesize.value,
    selectform.value
  );
  if (res.code) {
    //提示删除失败
    ElMessage.error("获取失败");
    return;
  }
  datalist.value = res.data;
  total.value = res.count;
  //获取申请列表
  // console.log("list", datalist);
  //清空表单
};

const sizeChange = async () => {
  //页面发生变化
  getApproveList();
};

onMounted(() => {
  getApproveList();
});

const dialogVisible = ref(false); //控制弹窗可见
const diglogDisable = ref(false); //控制禁用，但是这里应该只有禁用了
const diaFrom = ref({
  id: "",
  type: "",
  title: "",
  paperAbstract: "",
  participantMembers: "",
  teamRank: "",
  certificate: "", //但这个有可见性
  status: "", //但这个有可见性
  finalLevel: "", //也是可见性
});

const statusText = {
  0: "待审批",
  1: "审批通过",
  2: "审批失败",
  3: "提前结束",
  4: "等待认证",
  5: "认证成功",
  6: "认证失败",
};
const typeText = ["论文", "专利", "软著"];
const levelText = [
  "SCI一区",
  "SCI二区",
  "SCI三区",
  "SCI四区",
  "EI中文会议",
  "EI英文会议",
  "中文核心期刊",
  "中文普通期刊",
  "其他期刊",
];
//对应六个颜色
const statsColr = [
  "#9C27B0",
  "#409EFF",
  "#F56C6C",
  "#E6A23C",
  "#9C27B0",
  "#67C23A",
  "#F56C6C",
];
const handleClose = async () => {
  dialogVisible.value = false;
};

const preView = async (row) => {
  //用obssgin方法row对应的值赋给diaFrom
  dialogVisible.value = true;
  diglogDisable.value = true;
  console.log(row);
  diaFrom.value = JSON.parse(JSON.stringify(row));
  diaFrom.value.type = typeText[row.type];
  if (diaFrom.value.finalLevel != "") {
    diaFrom.value.finalLevel = levelText[diaFrom.value.finalLevel];
  }
  console.log(diaFrom.value);
  level.value = "";
};

const isPass = ref(""); //单个的，通过与否，全体的审批也可用
const level = ref(""); //单个的单个写，批量的另写表单

const passForm = ref({
  type: "", //方便判断的，下拉框，也是认证阶段
  ispass: "", //是否通过
  level: "", //等级，只有是论文且认定阶段才显示
});

const levelList = [
  { value: "SCI一区", label: "SCI一区" },
  { value: "SCI二区", label: "SCI二区" },
  { value: "SCI三区", label: "SCI三区" },
  { value: "SCI四区", label: "SCI四区" },
  { value: "EI中文会议", label: "EI中文会议" },
  { value: "EI英文会议", label: "EI英文会议" },
  { value: "中文核心期刊", label: "中文核心期刊" },
  { value: "中文普通期刊", label: "中文普通期刊" },
];

const PassApply = async (s) => {
  //单个同意
  const res = await postPaperAdminApplicate(diaFrom.value.id, s);
  if (res.code) {
    ElMessage.error("操作失败");
    return;
  }
  ElMessage.success("操作成功");
  getApproveList();
  dialogVisible.value = false;
};

const confirmApply = async (s) => {
  const idList = ref([]);
  idList.value.push(diaFrom.value.id);
  let res;
  // console.log("s", s);
  if (s == false) {
    //拒绝传空串
    if (userStore.userRole.includes("ROLE_ADMIN"))
      res = await postPaperAdminUpdate(diaFrom.value.id, 10, s);
    else res = await postPaperLevel(idList.value, 10, s);
  }
  //等级
  else {
    if (level.value == "" && diaFrom.value.type == "论文") {
      ElMessage.error("请选择等级");
      return;
    }
    const numlevel = level.value == "" ? 10 : levelSrtingToNum(level.value);
    if (userStore.userRole.includes("ROLE_ADMIN"))
      res = await postPaperAdminUpdate(diaFrom.value.id, numlevel, s);
    else res = await postPaperLevel(idList.value, numlevel, s);
  }
  if (res.code) {
    ElMessage.error("认定失败");
    return;
  }
  ElMessage.success("操作认定结果成功");
  level.value = "";
  dialogVisible.value = false;
  getApproveList();
};

import { saveAs } from "file-saver"; //文件流
import { remove } from "lodash";
const paperExport = async () => {
  if (datalist.value.length == 0) {
    ElMessage.error("无数据可导出");
    return;
  }
  await postPaperAdminExport(selectform.value)
    .then((response) => {
      saveAs(response, "论文/专利/软著详情.xlsx");
    })
    .catch((error) => {
      ElMessage.error("导出失败");
    });
};

const MulVisible = ref(false);
const MulhandleClose = async () => {
  MulVisible.value = false;
};

function valToList() {
  const list = ref([]);
  for (let i = 0; i < multipleSelection.value.length; i++) {
    list.value.push(multipleSelection.value[i].id);
  }
  return list.value;
}
const MulPass = async (s) => {
  const list = valToList();
  if (list.length == 0) {
    ElMessage.error("请选择要操作的申请");
    return;
  }
  const res = await postPaperAdminMulApplicate(list, s);
  if (res.code) {
    ElMessage.error("操作失败");
    return;
  }
  ElMessage.success("操作成功");
  await getApproveList();
};

const picExport = async () => {
  const list = valToList();
  if (list.length == 0) {
    ElMessage.error("请选择要操作的申请");
    return;
  }
  await postPaperAdminDownloadEvidence(list)
    .then((response) => {
      saveAs(response, "论文/专利/软著图片附件详情.zip");
    })
    .catch((error) => {
      ElMessage.error("导出失败");
    });
};
</script>

<template>
  <el-card class="box">
    <div class="top">
      <span style="font-size: 25px; color: #203857">论文/专利/软件审核</span>
      <el-button type="primary" @click="MulPass(true)"
        ><el-icon><EditPen /></el-icon>批量同意审批</el-button
      >
      <el-button type="danger" @click="MulPass(false)"
        ><el-icon><EditPen /></el-icon>批量拒绝审批</el-button
      >
      <el-button type="success" @click="picExport()" title="选择附件导出"
        ><el-icon><Folder /></el-icon>附件导出</el-button
      >
    </div>
    <el-form :model="selectform" ref="form" inline="true">
      <el-form-item label="申请类型">
        <el-select
          v-model="selectform.type"
          placeholder="请选择申请类型"
          style="height: 35px; width: 150px"
        >
          <el-option label="论文" value="0"></el-option>
          <el-option label="专利" value="1"></el-option>
          <el-option label="软著" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="申请状态">
        <el-select
          v-model="selectform.status"
          placeholder="请选择申请状态"
          style="height: 35px; width: 150px"
        >
          <!-- 0已提交，1已审批（通过），2已审批（未通过），3已结束(未获奖,流程结束)，4 已提交认定申请，5已审批认定申请 -->
          <el-option label="待审核" value="0"></el-option>
          <el-option label="审批通过" value="1"></el-option>
          <el-option label="审批失败" value="2"></el-option>
          <el-option label="提前结束" value="3"></el-option>
          <el-option label="等待认证" value="4"></el-option>
          <el-option label="认证成功" value="5"></el-option
          ><el-option label="认证失败" value="6"></el-option>
        </el-select>
      </el-form-item>
      <!-- 级别认定(0~3 SCI一二三四区, 4EI会议 , 5中文核心 , 6中文普刊 , 7其他 ) -->
      <el-form-item label="认定等级">
        <el-select
          v-model="selectform.finalLevel"
          placeholder="请选择认定等级"
          style="height: 35px; width: 150px"
          :disabled="selectform.type != 0"
        >
          <!-- 0已提交，1已审批（通过），2已审批（未通过），3已结束(未获奖,流程结束)，4 已提交认定申请，5已审批认定申请 -->
          <el-option
            v-for="item in levelList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="姓名">
        <!-- 存疑要不要是姓名 -->
        <el-input
          style="height: 32px; width: 120px"
          v-model="selectform.stuName"
          placeholder="请输入姓名"
        />
      </el-form-item>
      <el-form-item label="班级">
        <!-- 存疑要不要是姓名 -->
        <el-input
          style="height: 32px; width: 150px"
          v-model="selectform.stuClass"
          placeholder="请输入班级"
        />
      </el-form-item>
      <el-form-item label="申请时间段">
        <el-date-picker
          style="height: 32px; width: 230px"
          v-model="timestg"
          type="daterange"
          unlink-panels
          range-separator="To"
          start-placeholder="Start date"
          end-placeholder="End date"
          :shortcuts="shortcuts"
          :size="size"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="success"
          @click="paperExport()"
          title="控制筛选条件导出"
          ><el-icon><Promotion /></el-icon>详情导出</el-button
        >
        <el-button type="primary" style="width: 90px" @click="getApproveList"
          >筛选</el-button
        >
        <el-button style="width: 90px" @click="removeSelectForm"
          >清除筛选</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      :data="datalist"
      height="350px"
      stripe
      ref="multipleTableRef"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" :selectable="selectable" width="40" />
      <el-table-column
        type="index"
        label="序号"
        width="55"
        align="center"
      ></el-table-column>

      <el-table-column
        prop="createTime"
        label="申请时间"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="stuName"
        label="申请人"
        show-overflow-tooltip
        align="center"
      ></el-table-column>
      <el-table-column
        prop="uid"
        label="学号"
        show-overflow-tooltip
        align="center"
      ></el-table-column>
      <el-table-column
        prop="stuClass"
        label="班级"
        show-overflow-tooltip
        align="center"
      ></el-table-column>
      <el-table-column prop="type" label="申请类型" align="center"
        ><template #="{ row }">
          <span>{{ typeText[row.type] }}</span>
        </template></el-table-column
      >
      <el-table-column
        prop="teamRank"
        label="申请位次"
        align="center"
      ></el-table-column>
      <!-- <el-table-column prop="status" label="申请状态" align="center">
        <template #="{ row }">
          <span :style="{ color: statsColr[row.status] }">{{
            statusText[row.status]
          }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column
        prop="finalLevel"
        label="认定等级"
        show-overflow-tooltip
        align="center"
      ></el-table-column> -->
      <el-table-column prop="status" label="申请状态" align="center">
        <template #="{ row }">
          <span :style="{ color: statsColr[row.status] }">{{
            row.status != 5
              ? statusText[row.status]
              : row.finalLevel <= 7
              ? levelText[row.finalLevel]
              : statusText[row.status]
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right">
        <template #="{ row }">
          <el-button
            title="查看详情"
            type="primary"
            size="small"
            icon="View"
            circle
            plain
            @click="preView(row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
        @size-change="sizeChange"
        @current-change="getApproveList"
        :pager-count="9"
        v-model:current-page="pagenum"
        v-model:page-size="pagesize"
        :page-sizes="[1, 3, 5, 7, 9, 15, 30, 60]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        v-if="total > pagesize"
      />
    </div>
    <el-dialog
      v-model="dialogVisible"
      width="700"
      :before-close="handleClose"
      draggable
    >
      <template #header="{}">
        <div class="my-header">
          <img class="imgtitle" src="@/assets/images/logo.jpg" />
          <span class="titleClass">查看详情</span>
          <span
            v-if="diaFrom.status"
            class="titleendClass"
            :style="{ color: statsColr[diaFrom.status] }"
            >({{ statusText[diaFrom.status] }})</span
          >
        </div>
      </template>
      <el-form
        label-width="auto"
        :model="diaFrom"
        :disabled="diglogDisable"
        style="width: 650px"
      >
        <el-form-item label="申请类型">
          <el-select
            v-model="diaFrom.type"
            placeholder="请选择申请类型"
            style="height: 35px; width: 150px"
          >
            <el-option label="论文" value="0"></el-option>
            <el-option label="专利" value="1"></el-option>
            <el-option label="软著" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="diaFrom.title"></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <el-input
            v-model="diaFrom.paperAbstract"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
          ></el-input>
        </el-form-item>
        <el-form-item label="团队成员">
          <el-input
            v-model="diaFrom.participantMembers"
            placeholder="请用逗号分隔"
          ></el-input>
        </el-form-item>
        <el-form-item label="等级" v-if="diaFrom.type == `论文`">
          <el-input v-model="diaFrom.finalLevel"></el-input>
        </el-form-item>
        <el-form-item label="排名">
          <el-input
            v-model="diaFrom.teamRank"
            placeholder="只需要填写一个数字"
          ></el-input>
        </el-form-item>
        <el-form-item label="证书" v-if="diaFrom.certificate">
          <el-image
            :src="diaFrom.certificate"
            style="width: 100px; height: 100px"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="[diaFrom.certificate]"
            :initial-index="4"
            fit="cover"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div v-if="diaFrom.status == 0">
            <el-button @click="PassApply(false)">拒绝</el-button>
            <el-button type="primary" @click="PassApply(true)">
              通过
            </el-button>
          </div>
          <div v-if="checkRole(diaFrom.status)">
            <el-select
              v-model="level"
              placeholder="请选择认定等级"
              style="height: 35px; width: 180px; margin-right: 10px"
              v-if="diaFrom.type == `论文`"
            >
              <el-option
                v-for="item in levelList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-button type="primary" @click="confirmApply(true)">
              提交认定
            </el-button>
            <el-button @click="confirmApply(false)"> 不予认定 </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="MulVisible" width="500" :before-close="MulhandleClose">
    </el-dialog>
  </el-card>
</template>

<style scoped lang="scss">
.box {
  padding: 15px;
  // //开启相对定位
  // position: relative;
  // .el-pagination {
  //   position: absolute;
  //   bottom: 25px;
  // }
  .el-table {
    margin-bottom: 2vh;
  }
}
.top {
  display: flex;
  width: 100%;

  height: 50px;
  line-height: 50px;

  //垂直居中
  align-items: center;
  .el-button {
    margin-left: 20px;
  }
  margin-bottom: 15px;
}
.my-header {
  display: flex;
  height: 50px;
  line-height: 50px;
  .titleClass {
    font-size: 25px;
  }
  .imgtitle {
    width: 50px;
    height: 50px;
    margin-right: 10px;
  }
  .titleendClass {
    margin-left: 10px;
    font-size: 20px;
  }
}
</style>
